package controller.Operation;

import model.NormalUser;
import util.RecordDao;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @Question Renew
 * @Date 2022/12/19 20:00
 * @Solution
 */
public class Renew {
    public static void bookRenew(NormalUser user , JTable bookTable, DefaultTableModel bookModel, DefaultTableModel recordModel,JTable recordTable) throws ParseException {

        //检查是否有行被选中
        int row = recordTable.getSelectedRow();
        if(row==-1) {
            JOptionPane.showMessageDialog(null, "请选择需要续借的书籍!");
            return;
        }
        //获取到该行记录的id
        int id=(int) recordModel.getValueAt(row,0);
        Date date = (Date) recordModel.getValueAt(row,4);
        //date转LocalDateTime
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime oldEnd =instant.atZone(zoneId).toLocalDateTime();
        //选择需要续借的天数
        int choice = JOptionPane.showOptionDialog(null, "请选择需要续借的天数", "天数选择对话框",
                JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,   null, new String[]{"7天","14天","30天"}, "7天");
        //计算到期天数
        int day;
        if(choice==0) {
            day=7;
        } else if(choice==1) {
            day=14;
        } else {
            day=30;
        }
        LocalDateTime end = oldEnd.plusDays(day);
        //LocalDateTime转Date
        Date endDate = Date.from( end.atZone( ZoneId.systemDefault()).toInstant());
        //Date转String
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fm = simpleDateFormat2.format(endDate);
        //修改归还日期
        RecordDao recordDao = new RecordDao();
        recordDao.reviseInDate(id,fm);
        //刷新
        Show.showByUserIdRecord(recordModel, user.getId());
        Show.showAllBook(bookModel);
        JOptionPane.showMessageDialog(null, "续借成功！");
    }
}
